package com.example.demo;

import java.awt.event.MouseWheelEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Hyperv {

    public static void main(String[] args) {

        String vmName = "TestVM";
        String vmPath = "D:\\Hyper-v\\vhdx";
        int memory = 1024;
        int diskSize = 10;  // 单位为GB
        String isoPath = "D:\\CentOS-DVD\\Win11_23H2_Chinese_Simplified_x64v2.iso";

        vmCreate(vmName, vmPath, memory, diskSize,isoPath);
    }

    public static String vmCreate(String vmName, String vmPath, int memory, int diskSize, String isoPath) {
        try {
            // 确保CreateVM.ps1文件的路径正确
            String scriptPath = "D:\\CreateHyperv\\CreateVM.ps1";
            String command = String.format("powershell.exe -ExecutionPolicy Bypass -File \"%s\" -vmName \"%s\" -vmPath \"%s\" -Memory %d -diskSize %d -isoPath  \"%s\" " ,
                    scriptPath, vmName, vmPath, memory, diskSize, isoPath);
            Process powerShellProcess = Runtime.getRuntime().exec(command);

            BufferedReader inputReader = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream()));
            String line;
            String Message = null;

            int i = 0;

            while ((line = inputReader.readLine()) != null) {
                i ++;
                if (i == 4) {
                    Message = line;
//                    System.out.println(line);
                }
                System.out.println(line);
            }

            BufferedReader errorReader = new BufferedReader(new InputStreamReader(powerShellProcess.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = powerShellProcess.waitFor();
            System.out.println("PowerShell script exited with code: " + exitCode);

            return Message;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

//Boot failure Reboot and Select proper Boot device ot Insert Boot Media in selected Boot device